package pe.edu.upc.dai.grupo4.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import pe.edu.upc.dai.grupo4.model.Moneda;
import pe.edu.upc.dai.grupo4.utils.ConnectionUtils;
import pe.edu.upc.dai.grupo4.utils.DaoException;

/**
 *
 * @author Tito Luyo Murata
 */
public class MonedaDaoImpl implements MonedaDao {

    public Moneda selectPorCodMoneda(int CodMoneda) {
        Moneda result = null;
        Connection connection = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        try {
            connection = ConnectionUtils.getConnection();
            st = connection.prepareStatement("{call dbo.usp_Moneda_SEL_x_codMoneda(?)}");
            st.setInt(1, CodMoneda);
            rs = st.executeQuery();

            while (rs.next()) {
                result = this.getData(rs);
            }
        } catch (SQLException e) {
            throw new DaoException(e);
        } finally {
            ConnectionUtils.closeResultSet(rs);
            ConnectionUtils.closeStatement(st);
            ConnectionUtils.closeConnection(connection);
        }
        return result;
    }

    public List<Moneda> select() {
        List<Moneda> result = new ArrayList<Moneda>();
        Connection connection = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        try {
            connection = ConnectionUtils.getConnection();
            st = connection.prepareStatement("{call dbo.usp_Monedas_SEL}");
            rs = st.executeQuery();

            while (rs.next()) {
                result.add(this.getData(rs));
            }
        } catch (SQLException e) {
            throw new DaoException(e);
        } finally {
            ConnectionUtils.closeResultSet(rs);
            ConnectionUtils.closeStatement(st);
            ConnectionUtils.closeConnection(connection);
        }
        return result;
    }

    private Moneda getData(ResultSet rs) throws SQLException {
        Moneda result = null;
        result = new Moneda(
                rs.getInt("CodMoneda"),
                rs.getString("NombreMoneda"));
        return result;
    }
}
